import { addTextFieldPropertiesToFeatures } from '../../utils/LayerUtil';
import { getSblxBySbzlx } from '../../../../mapUtils/SblxUtil';
import { formatDeviceFeature } from '../../../../mapUtils/StyleListUtil';
import { parse } from '../../../../mapUtils/Geojson2WktUtil';
import { projectLngLatToWebMercator } from '../../../../mapUtils/CoordinateUtil';
import { debounce } from 'throttle-debounce';
import IGridTool from '../IGridTool';
import Prefix from '../../constant/Prefix';

/**
 * 抽稀电网图层工具箱
 * @implements {IGridTool}
 */
class ThinGridTool extends IGridTool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'ThinGridTool';
    this.desc = '抽稀电网图层工具箱';
    this.layeridPrefix = Prefix['ThinGrid'];
    this.defaultSchemaid = 2;
    // this._refresh = this.refresh.bind(this);
    this._refresh = debounce(this.THROTTLE_DURATION, () => {
      // if(this.startzoom) {
      //   this.startzoom = false;
      //   return;
      // }
      this.refresh(this.useNewService, this.option);
    }).bind(this);
  }

  /**
   * 刷新现状图层
   * @override
   */
  refresh(useNewService, option) {
    this.option = option;
    this.setCurrentGridTool(this);
    if (this.isLocked()) {
      return;
    }
    // 当前请求时间
    let currentRequestTime = this.latestRequestTime = new Date().getTime();
    // 获取当前缩放等级下配置的图层列表
    this.getApi().PwghGhsjScTxfw.figure.get_figure_getEquitpType({
      params: {
        zoom: this.getTool('BaseMapTool').getZoom(),
        schemaid: this.searchOption.schemaid || this.defaultSchemaid
      }
    })
      .then((data) => {
        // 过期请求不处理
        if (this._isOutDate(currentRequestTime)) {
          return;
        }
        let sbzlxs = data.datas;
        let promiselist = [];
        // 获取范围、缩放等级
        let extent = this.getTool('BaseMapTool').getBounds();
        let shape = parse(
          turf.polygon(projectLngLatToWebMercator(turf.bboxPolygon(extent).geometry.coordinates)).geometry
        );
        // 拼接请求数据
        sbzlxs.forEach((sbzlx) => {
          promiselist.push(
            new Promise((resolve) => {
              let params = Object.assign({}, this.searchOption, {
                zoom: this.getTool('BaseMapTool').getZoom(),
                sblx: sbzlx.sblx,
                shape: shape,
                oid: sbzlx.oid,
                schema: this.searchOption.schema || this.getConfig().get('SCHEMA'),
                sssdw: this.searchOption.ssdw
              });
              this.getApi().PwghGhsjScTxfw.jhfigure.post_jhfigure_getSimpleFigureShow({ params: params })
                .then((res) =>
                  resolve({ sblx: sbzlx.sblx, res })
                )
                .catch(() =>
                  resolve({
                    sblx: sbzlx.sblx,
                    res: {
                      datas: [],
                      'resp_msg': '调用服务出错'
                    }
                  })
                );
            })
          );
        });
        Promise.all(promiselist).then((resList) => {
          // 过期请求不处理
          if(!this._isOutDate(currentRequestTime)) {
            this._showBySgmapLayer(resList, option);
            this.finishRender();
          }
        });
      });
  }

  /**
   * 采用思极地图的形式绘制图层
   * @override
   * @param {Array} resList 图形数据
   * @ignore
   */
  _showBySgmapLayer(resList, option) {
    let features = [];
    let zoom = this.getTool('BaseMapTool').getZoom();
    console.log(option);
    let offset = option?.maxWidth ? Math.round(327680 / Math.pow(option.maxWidth, zoom)) : Math.round(327680 / Math.pow(2, zoom));
    console.log(offset);
    resList.forEach((res) => {
      if (res.res.resp_code !== 200) {
        return;
      }
      let sblx = res.sblx;
      let datas = res.res.datas || [];
      datas.forEach((item) => {
        let shapejson = item.shapejson;
        if (shapejson) {
          let lineNum = item.line_type;
          if (lineNum > 1) {
            let oid = item.oid.split(',');
            let sbzlx = item.sbzlx.split(',');
            let dydj = item.dydj.split(',');
            let kstype = item.kstype.split(',');
            let quitDate = item.quit_date.split(',');
            let sbid = item.sbid.split(',');
            let sbmc = item.sbmc.split(',');
            let ssxl = item.ssxl.split(',');
            let tynf = item.tynf.split(',');
            let zt = item.zt.split(',');
            let baseline = JSON.parse(shapejson);
            let offsetNum = (lineNum - 1) / 2;
            for (let i = 0, j = -offsetNum * offset; i < lineNum; i++, j = j + offset) {
              let line = Object.assign({}, item, {
                oid: oid[i],
                // sbzlx: this.formatSbzlx(sbzlx[i]),
                sbzlx: sbzlx[i],
                dydj: Number(dydj[i]),
                kstype: kstype[i],
                'quit_date': quitDate[i],
                sbid: sbid[i],
                sbmc: sbmc[i],
                ssxl: ssxl[i],
                tynf: tynf[i],
                zt: zt[i]
              });
              line.geometry = turf.lineOffset(baseline, j, { units: 'meters' }).geometry;
              // line.sblx = getSblxBySbzlx(line.sbzlx);
              // line.transSbzlx = line.sbzlx;
              line.sblx = sblx;
              line.transSbzlx = (line.versionid > 0 || (line.versionid + '').indexOf('0') !== 0)
                ? Number('8' + line.sbzlx)
                : Number(line.sbzlx);
              // let style = getStyle(line, { zoom: zoom });
              let feature = formatDeviceFeature(line);
              features.push(feature);
            }
          } else {
            // item.sbzlx = this.formatSbzlx(item.sbzlx);
            item.dydj = Number(item.dydj);
            item.geometry = JSON.parse(shapejson);
            // item.sblx = getSblxBySbzlx(item.sbzlx);
            // item.transSbzlx = item.sbzlx;
            item.sblx = sblx;
            item.transSbzlx = item.versionid > 0
              ? Number('8' + item.sbzlx)
              : Number(item.sbzlx);
            // let style = getStyle(item, { zoom: zoom });
            let feature = formatDeviceFeature(item);
            features.push(feature);
          }
        } else {
          // this.info(item.sbzlx, item.oid, "设备无返回坐标信息");
        }
      });
    });
    features = addTextFieldPropertiesToFeatures(features, 'sbmc');
    var featureCollection = turf.featureCollection(features);
    // 数据过滤器
    if(this.dataFilter) {
      featureCollection = this.dataFilter(featureCollection);
    }
    this.getMap().getSource(this._sourceId).setData(featureCollection);
    if(this.events.datachange) {
      this.events.datachange(this.getRenderedFeatures());
    }
    this.getEventBus().$emit('gridtool.datachange', this.getRenderedFeatures());
  }

  /**
   * 格式化设备子类型
   * @param {Array|Number} sbzlx 设备子类型
   * @ignore
   */
  formatSbzlx(sbzlx) {
    return Number(sbzlx.toString().substring(1));
  }
}

export default ThinGridTool;
